package com.foocus.foocuscloud.common.filter;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Enumeration;

@WebFilter(value = "/*")
public class LogFilter implements Filter {

    private static final Logger LOGGER = LogManager.getLogger(LogFilter.class);

    public void init(FilterConfig filterConfig) {
        LOGGER.info(">>>>>>>>>>>>>>>CodeMine-Starter Start.<<<<<<<<<<<<<<<");
    }

    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
            throws IOException, ServletException {

        long entranceTime = System.currentTimeMillis();
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String requestURI = request.getRequestURI();

        Enumeration<String> paramNames = request.getParameterNames();
        StringBuilder paramLog = new StringBuilder();
        while (paramNames.hasMoreElements()) {
            String param = paramNames.nextElement();
            String paramValue = request.getParameter(param);
            paramLog.append(param).append(": ").append(paramValue);
            if (paramNames.hasMoreElements()) {
                paramLog.append(",");
            }
        }

        filterChain.doFilter(request, response);
        long costTime = System.currentTimeMillis() - entranceTime;
        LOGGER.info("Request Uri=[{}], Params=[{}], Request Cost Time: {}ms", requestURI, paramLog.toString(), costTime);
    }

    public void destroy() {
        LOGGER.info(">>>>>>>>>>>>>>>CodeMine-Starter Shutdown.<<<<<<<<<<<<<<<");
    }
}
